let http = require("http")
let fs = require("fs")
let url = require("url")
let qs = require("querystring")

let userDb = {}

let server = http.createServer((req,res)=>{
    //get参数
    let {query,pathname} = url.parse(req.url,true)    
    //post参数
    let postdata = ''
    req.on('data',data=>{
        postdata += data
    })
    req.on('end',err=>{
        if(err){
            res.writeHeader(401)
            res.write("POST DATA ERROR")
            res.end()
            return
        }
        let {account,passwd} = qs.parse(postdata)
        switch (pathname) {
            case '/reg':
                if(userDb[account]){
                    res.write('{"msg":"already exist account"}')
                }else{
                    userDb[account] = passwd
                    res.write('{"msg":"success"}')
                }
                res.end()
                break;
            case '/login':
                if(userDb[account] && userDb[account] == passwd){
                    res.write('{"msg":"success"}')
                }else{
                    userDb[account] = passwd
                    res.write('{"msg":"account or passwd error"}')
                }
                res.end()
                break;
            default:
                fs.readFile(`www${pathname}`,(err,data)=>{
                    if(err){
                        res.writeHeader(404)
                        res.write('Not Found')
                    }else{
                        res.write(data)
                    }
                    res.end()
                })
                break;
        }
    })
})

server.listen(8080)
